# -*- coding: UTF-8 -*-
"""
玩家成绩统计[会在每次结束比赛时调用]
"""
import threading
import json
import os
import bs
import urllib2

# 数据库路径
DATA_PATH = bs.getEnvironment()['systemScriptsDirectory'] + "/data"

# 统计文件路径
stats_file = DATA_PATH + "/stats.json" 

def update(score_set):
    """
   Given a Session's ScoreSet, tallies per-account kills, scores, deaths, multiKills, and names
   and passes them to a background thread to process and
   store.
   """
    # look at score-set entries to tally per-account kills, deaths and scores for this round

    account_kills = {}
    account_deaths = {}
    account_scores = {}
    account_mkc = {}
    account_ln = {}
    account_c = {}
    for p_entry in score_set.getValidPlayers().values():
        account_id = p_entry.getPlayer().get_account_id()
        if account_id is not None:
            account_kills.setdefault(account_id, 0)  # make sure exists
            account_kills[account_id] += p_entry.accumKillCount
            account_deaths.setdefault(account_id, 0)  # make sure exists
            account_deaths[account_id] += p_entry.accumKilledCount
            account_scores.setdefault(account_id, 0)  # make sure exists
            account_scores[account_id] += p_entry.accumScore
            account_mkc.setdefault(account_id, 0)  # make sure exists
            account_mkc[account_id] += p_entry._multiKillCount
            account_ln.setdefault(account_id, "")  # make sure exists
            account_ln[account_id] = p_entry.nameFull
            account_c.setdefault(account_id, "")  # make sure exists
            account_c[account_id] = str(p_entry.character)
        # Ok; now we've got a dict of account-ids and kills, scores, deaths, multiKills, and names.
        # Now lets kick off a background thread to load existing scores
        # from disk, do display-string lookups for accounts that need them,
        # and write everything back to disk (along with a pretty html version)
        # We use a background thread so our server doesn't hitch while doing this.
    UpdateThread(account_kills, account_deaths, account_scores, account_mkc, account_ln, account_c).start()


class UpdateThread(threading.Thread):
    def __init__(self, account_kills, account_deaths, account_scores, account_mkc, account_ln, account_c):
        threading.Thread.__init__(self)
        self._account_kills = account_kills
        self.account_deaths = account_deaths
        self.account_scores = account_scores
        self.account_mkc = account_mkc
        self.account_ln = account_ln
        self.account_c = account_c

    def run(self):
        # pull our existing stats from disk
        if os.path.exists(stats_file):
            with open(stats_file) as f:
                stats = json.loads(f.read())
        else:
            stats = {}

        # now add this batch of kills, deaths and scores to our persistant stats
        for account_id, kill_count in self._account_kills.items():
            # add a new entry for any accounts that dont have one
            if account_id not in stats:
                # also lets ask the master-server for their account-display-str.
                # (we only do this when first creating the entry to save time,
                # though it may be smart to refresh it periodically since
                # it may change)
                url = 'http://bombsquadgame.com/accountquery?id=' + account_id
                response = json.loads(
                    urllib2.urlopen(urllib2.Request(url)).read())
                name_html = response['name_html']
                stats[account_id] = {'kills': 0, 'deaths': 0, 'scores': 0, 'mkc': 0, 'name_html': name_html,
                                     'lastName': "", 'games': 0, 'aid': "", 'lastCharacter': ""}
            # now increment their kills whether they were already there or not
            stats[account_id]['kills'] += kill_count
            # also incrementing the games played and adding the id
            stats[account_id]['games'] += 1
            stats[account_id]['aid'] = str(account_id)
        for account_id, killed_count in self.account_deaths.items():
            # add a new entry for any accounts that dont have one
            if account_id not in stats:
                # also lets ask the master-server for their account-display-str.
                # (we only do this when first creating the entry to save time,
                # though it may be smart to refresh it periodically since
                # it may change)
                url = 'http://bombsquadgame.com/accountquery?id=' + account_id
                response = json.loads(
                    urllib2.urlopen(urllib2.Request(url)).read())
                name_html = response['name_html']
                stats[account_id] = {'kills': 0, 'deaths': 0, 'scores': 0, 'mkc': 0, 'name_html': name_html,
                                     'lastName': "", 'games': 0, 'aid': "", 'lastCharacter': ""}
            # now increment their deaths whether they were already there or not
            stats[account_id]['deaths'] += killed_count
        for account_id, score in self.account_scores.items():
            # add a new entry for any accounts that dont have one
            if account_id not in stats:
                # also lets ask the master-server for their account-display-str.
                # (we only do this when first creating the entry to save time,
                # though it may be smart to refresh it periodically since
                # it may change)
                url = 'http://bombsquadgame.com/accountquery?id=' + account_id
                response = json.loads(
                    urllib2.urlopen(urllib2.Request(url)).read())
                name_html = response['name_html']
                stats[account_id] = {'kills': 0, 'deaths': 0, 'scores': 0, 'mkc': 0, 'name_html': name_html,
                                     'lastName': "", 'games': 0, 'aid': "", 'lastCharacter': ""}
            # now increment their scores whether they were already there or not
            stats[account_id]['scores'] += score
        for account_id, mkc in self.account_mkc.items():
            # add a new entry for any accounts that dont have one
            if account_id not in stats:
                # also lets ask the master-server for their account-display-str.
                # (we only do this when first creating the entry to save time,
                # though it may be smart to refresh it periodically since
                # it may change)
                url = 'http://bombsquadgame.com/accountquery?id=' + account_id
                response = json.loads(
                    urllib2.urlopen(urllib2.Request(url)).read())
                name_html = response['name_html']
                stats[account_id] = {'kills': 0, 'deaths': 0, 'scores': 0, 'mkc': 0, 'name_html': name_html,
                                     'lastName': "", 'games': 0, 'aid': "", 'lastCharacter': ""}
            # now increment their mkc whether they were already there or not
            if stats[account_id]['mkc'] < mkc:
                stats[account_id]['mkc'] = mkc
        for account_id, ln in self.account_ln.items():
            # add a new entry for any accounts that dont have one
            if account_id not in stats:
                # also lets ask the master-server for their account-display-str.
                # (we only do this when first creating the entry to save time,
                # though it may be smart to refresh it periodically since
                # it may change)
                url = 'http://bombsquadgame.com/accountquery?id=' + account_id
                response = json.loads(
                    urllib2.urlopen(urllib2.Request(url)).read())
                name_html = response['name_html']
                stats[account_id] = {'kills': 0, 'deaths': 0, 'scores': 0, 'mkc': 0, 'name_html': name_html,
                                     'lastName': "", 'games': 0, 'aid': "", 'lastCharacter': ""}
            # now add their last name whether they were already there or not
            stats[account_id]['lastName'] = ln
        for account_id, c in self.account_c.items():
            # add a new entry for any accounts that dont have one
            if account_id not in stats:
                # also lets ask the master-server for their account-display-str.
                # (we only do this when first creating the entry to save time,
                # though it may be smart to refresh it periodically since
                # it may change)
                url = 'http://bombsquadgame.com/accountquery?id=' + account_id
                response = json.loads(
                    urllib2.urlopen(urllib2.Request(url)).read())
                name_html = response['name_html']
                stats[account_id] = {'kills': 0, 'deaths': 0, 'scores': 0, 'mkc': 0, 'name_html': name_html,
                                     'lastName': "", 'games': 0, 'aid': "", 'lastCharacter': ""}
            # now add their last character whether they were already there or not
            stats[account_id]['lastCharacter'] = c

        # dump our stats back to disk
        with open(stats_file, 'w') as f:
            f.write(json.dumps(stats))

        # lastly, write a pretty html version.
        # our stats url could point at something like this...
        entries = [(a['scores'], a['mkc'], a['kills'], a['deaths'], a['name_html'], a['lastName'], a['games'], a['aid'],
                    a["lastCharacter"]) for a in stats.values()]
        # this gives us a list of scores/names sorted high-to-low
        entries.sort(reverse=True)
        json_data = {}
        rank = 0
        toppers = {}
        pStats = {}
        for entry in entries:
            rank += 1
            scores = str(entry[0])
            mkc = str(entry[1])
            kills = str(entry[2])
            deaths = str(entry[3])
            name = entry[4].encode('utf-8')
            ln = entry[5].encode('utf-8')
            games = str(entry[6])
            aid = str(entry[7])
            lc = str(entry[8])
            if rank < 11:
                toppers[str(aid)] = ("#" + str(rank))
            pStats[str(aid)] = {"rank": str(rank),
                                "scores": str(scores),
                                "games": str(games),
                                "deaths": str(deaths),
                                "kills": str(kills)}
            json_data[str(rank)] = {
                "icon_url": str(str(name).split("\'>")[0]).split("src='")[1],
                "name": str(name).split("\'>")[1],
                "last_used_name": str(ln),
                "games_played": str(games),
                "account_id": str(aid),
                "rank": str(rank),
                "scores": str(scores),
                "multi_kill_count": str(mkc),
                "kills": str(kills),
                "deaths": str(deaths)
            }
            try:
                kd = str(float(kills) / float(deaths))[:3]
            except Exception:
                kd = "0"
            try:
                average_score = str(float(scores) / float(games))[:3]
            except Exception:
                average_score = "0"
            
        f = open(DATA_PATH + "/toppers.json", "w")
        f.write(json.dumps(toppers))
        f.close()
        f2 = open(DATA_PATH + "/player_stats.json", "w")
        f2.write(json.dumps(pStats))
        f2.close()

        print('排名系统 -> 添加了 ' + str(len(self._account_kills)) + ' 名玩家的游戏数据！')
